package com.eunion.boot;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.BasicErrorController;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.ModelAndView;

/**
 * 自定义错误控制器,后续研究异常源码及如下文章
 * https://my.oschina.net/angerbaby/blog/595367
 * https://github.com/spring-projects/spring-boot/blob/4f7752d4672c3994a05dd3fb3d6e699040117ae0/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/BasicErrorController.java
 * http://blog.csdn.net/lzwglory/article/details/17252099
 * http://git.oschina.net/devchenx/SpringBootDemo/blob/master/src/main/java/cn/chace/www/web/MyErrorController.java/?dir=0&filepath=src/main/java/cn/chace/www/web/MyErrorController.java&oid=257ab530e4f5e2b77de0b96c788985b2efebefe8&sha=8a3df329edef827423a8a1cf8df4c87ff973ddab
 * http://www.open-open.com/lib/view/open1446607376779.html
 *
 * @date 2015/12/30
 */
//@Controller //不可缺失
//@ControllerAdvice
public class SysErrorController extends BasicErrorController {

	private static final Logger LOGGER = LoggerFactory.getLogger(SysErrorController.class);

	@Autowired
	public SysErrorController(ServerProperties serverProperties) {
		super(new DefaultErrorAttributes(), serverProperties.getError());
	}

	/**
	 * 覆盖默认的Json响应
	 */
	@Override
	public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
		Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
		HttpStatus status = getStatus(request);
		LOGGER.error(body.toString());
		//输出自定义的Json格式
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("status", false);
		map.put("msg", body.get("message"));
		return new ResponseEntity<Map<String, Object>>(map, status);
	}

	/**
	 * 覆盖默认的HTML响应
	 */
	@Override
	public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
		response.setStatus(getStatus(request).value());
		Map<String, Object> model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML));
		//指定自定义的视图
		//org.springframework.security.access.AccessDeniedException
		return new ModelAndView("error", model);
	}
}
